var LM = {};
(function(){
    LM.nav = {
        group: [],
        activeGroupId: null,
        opMode: '',
        opId:'',
        refreshAllGroup: function(){
            LM.ajax('/nav/group', null, function(result){
                LM.nav.group = result;
                if(LM.nav.group.length > 0){
                    var groupHtml = '';
                    $(LM.nav.group).each(function(i,n){
                        if(i === 0){
                            groupHtml += '<span data-group-id="'+this.id+'" class="nav-group nav-group-active"><i class="'+this.icon+'" style="margin-right: 10px;"></i>'+this.name+'</span>';
                        }else{
                            groupHtml += '<span data-group-id="'+this.id+'" class="nav-group"><i class="'+this.icon+'" style="margin-right: 10px;"></i>'+this.name+'</span>';
                        }
                    });
                    $("#nav-left-div").html(groupHtml)
                    LM.nav.activeGroupId = LM.nav.group[0].id;
                    LM.nav.refreshItem(LM.nav.activeGroupId);
                }else {
                    $("#nav-left-div").html('');
                    $("#nav-right-div").html('');
                }
                $("#nav-left-div span").on('click', function(){
                    $("#nav-left-div span").each(function(){
                        $(this).removeClass('nav-group-active');
                    });
                    $(this).addClass('nav-group-active');
                    LM.nav.selectGroup(this);
                });
            })
        },
        refreshItem: function(groupId){
            const iconUrl = LM.cookie.getCookie("iconUrl")
            $(this.group).each(function(){
                if(this.id === groupId){
                    var itemHtml = '';
                    $(this.navItems).each(function(){
                        itemHtml += '<div data-item-url="'+this.url+'" data-item-id="'+this.id+'" class="nav-item">';
                        if(this.logo){
                            itemHtml += '<img src="' + this.logo + '" alt="" class="nav-item-logo">';
                        }else {
                            itemHtml += '<img src="' + iconUrl + this.url +'" alt="" class="nav-item-logo">';
                        }
                        itemHtml += '<span class="nav-item-desc">'+this.name+'</span>';
                        itemHtml += '</div>';
                    });
                    $("#nav-right-div").html(itemHtml)
                }
            });
            $(".nav-item").on('click', function(){
                LM.nav.selectItem(this);
            });
            this.bindMenu();
        },
        getGroup: function(groupId){
            var currentGroup = null;
            $(this.group).each(function(){
                if(this.id === groupId){
                    currentGroup = this;
                    return false;
                }
            });
            return currentGroup;
        },
        getItem: function(itemId){
            var currentItem = null;
            $(this.group).each(function(){
                $(this.navItems).each(function(){
                    if(this.id === itemId){
                        currentItem = this;
                        return false;
                    }
                });
                if(currentItem){
                    return false;
                }
            });
            return currentItem;
        },
        selectGroup: function(element){
            this.activeGroupId = $(element).attr('data-group-id');
            this.refreshItem(this.activeGroupId);
        },
        selectItem: function(element){
            var itemUrl = $(element).attr('data-item-url');
            window.open(itemUrl);
        },
        addGroup: function(){
            $('#group-slider').animate({
                'right': 0
            });
        },
        addItem: function(){
            $("#groupId").val(this.activeGroupId);
            $('#item-slider').animate({
                'right': 0
            });
        },
        editGroup: function(data){
            LM.form.setData('#group-form', data);
            $('#group-slider').animate({
                'right': 0
            });
        },
        editItem: function(data){
            data.groupId = this.activeGroupId;
            LM.form.setData('#item-form', data);
            $('#item-slider').animate({
                'right': 0
            });
        },
        delGroup: function(data){
            LM.ajax('/nav/group/del', data, function(result){
                alert('操作成功!');
                LM.nav.refreshAllGroup();
            },'post');
        },
        delItem: function(data){
            LM.ajax('/nav/item/del', data, function(result){
                alert('操作成功!');
                LM.nav.refreshAllGroup();
            },'post');
        },
        closeSlider: function(){
            LM.form.clear('#group-form')
            LM.form.clear('#item-form')
            $('#group-slider').animate({
                'right': -700
            });
            $('#item-slider').animate({
                'right': -700
            });
        },
        saveGroup: function(){
            var groupData = LM.form.getData('#group-form');
            LM.ajax("/nav/group/save", groupData, function(res){
                alert("操作成功!")
                LM.nav.refreshAllGroup();
                LM.nav.closeSlider();
            }, "post");
        },
        saveItem: function(){
            var itemData = LM.form.getData('#item-form');
            LM.ajax("/nav/item/save", itemData, function(res){
                alert("操作成功!")
                LM.nav.refreshAllGroup();
                LM.nav.closeSlider();
            }, "post");
        },
        bindFn: function(ev) {
            var menu = document.getElementById("r_menu")
            var oEvent = ev || event;
            var groupId = oEvent.currentTarget.dataset.groupId;
            var itemId = oEvent.currentTarget.dataset.itemId;
            if(itemId){
                LM.nav.opId = itemId;
                LM.nav.opMode = 'item';
            }else if(groupId){
                LM.nav.opId = groupId;
                LM.nav.opMode = 'group';
            }
            //自定义的菜单显示
            menu.style.display = "block";
            //让自定义菜单随鼠标的箭头位置移动
            menu.style.left = oEvent.clientX + "px";
            menu.style.top = oEvent.clientY + "px";
            ev.preventDefault();
            return false;
        },
        bindMenu: function(){
            $(".nav-group").contextmenu(LM.nav.bindFn);
            $(".nav-item").contextmenu(LM.nav.bindFn);
            document.onclick = function() {
                document.getElementById("r_menu").style.display = "none";
            }
        },
        editMenu: function(){
            switch (this.opMode) {
                case "item":
                    var currentItem = this.getItem(this.opId);
                    this.editItem(currentItem);
                    break;
                case "group":
                    var currentGroup = this.getGroup(this.opId);
                    this.editGroup(currentGroup);
                    break;
            }
        },
        delMenu: function(){
            switch (this.opMode) {
                case "item":
                    var currentItem = this.getItem(this.opId);
                    this.delItem(currentItem);
                    break;
                case "group":
                    var currentGroup =  JSON.parse(JSON.stringify(this.getGroup(this.opId)));
                    currentGroup.navItems = undefined;
                    this.delGroup(currentGroup);
                    break;
            }
        }
    }
    LM.ajax = function(url, data, Fn, method){
        $.ajax({
            url: url,
            data: data,
            headers:{'Authorization':LM.cookie.getCookie("access_token")},
            type: method || 'get',
            success: function(re){
                if(re.status === 200){
                    Fn(re.body);
                }else if(re.status === 401 || re.status === 403){
                    alert('登录信息失效!');
                    LM.cookie.clearCookie("access_token");
                    location.href = "/loginPage";
                }else{
                    alert('操作失败!');
                }
            }
        });
    }
    LM.iconBoxShow = function(){
        $('#icon-box').show();
    };
    LM.iconBoxHide = function(){
        $('#icon-box').hide();
    };
    LM.form = {
        getData: function(elementId){
            var groupObj = {}
            $(elementId + ' input').each(function(){
                groupObj[this.name] = this.value;
            });
            return groupObj;
        },
        setData: function(elementId, data){
            $(elementId + ' input').each(function(){
                this.value = data[this.name];
            });
        },
        clear: function(elementId){
            $(elementId + ' input').each(function(){
                this.value = '';
            });
        }
    }
    LM.cookie = {
        // 设置cookie
        setCookie: function (name, value, expireDays) {
            var expireDate = new Date();
            expireDate.setDate(expireDate.getDate() + expireDays || 1);
            document.cookie = name + "=" + escape(value) + ";expires=" + expireDate.toGMTString() + ";path=/";
        },
        // 读取cookie
        getCookie: function(name) {
            if (document.cookie.length > 0)     {
                c_start = document.cookie.indexOf(name + "=")
                if (c_start !== -1){
                    c_start = c_start + name.length + 1
                    c_end = document.cookie.indexOf(";", c_start)
                    if (c_end === -1)
                        c_end = document.cookie.length
                    return unescape(document.cookie.substring(c_start, c_end))
                }
            }
            return ""
        },
        clearCookie: function (name) {
            this.setCookie(name, "", -1);
        }
    }
    if(!LM.cookie.getCookie("access_token")){
        document.location.href = '/loginPage';
    }
})(LM);